﻿using Sean.Core.SnowFlake;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OrderSystem
{
    class GoodsDao
    {
        public GoodsDao() { }
        /*
        public int add(OrderDetails orderDetails)
        {
            try
            {
                using (var db = new OrderContext())
                {
                    //由于外键  必须有一个orderId   所以直接添加会失败
                    db.OrderDetails.Add(orderDetails);
                    return db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("添加失败!");
                Console.WriteLine(e.Message);
                return 0;
            }
        }
        public int remove(long id)
        {
            try
            {
                using(var db = new OrderContext())
                {
                    var good = db.Goods.FirstOrDefault(p => p.Id == id);
                    if (good != null)
                    {
                        db.Goods.Remove(good);
                        return db.SaveChanges();
                    }
                    else
                    {
                        Console.WriteLine("商品不存在!");
                        return 0;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("删除失败!");
                Console.WriteLine(e.Message);
                return 0;
            }
        }
        public int update(long id, Goods newGood)
        {
            try
            {
                using (var db = new OrderContext())
                {
                    var curGood = db.Goods.FirstOrDefault(p => p.Id == id);
                    if (curGood != null)
                    {
                        db.Goods.Remove(curGood);
                        db.Goods.Add(newGood);
                        return db.SaveChanges();
                    }
                    else
                    {
                        Console.WriteLine("商品不存在!");
                        return 0;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("修改失败!");
                Console.WriteLine(e.Message);
                return 0;
            }
        }
        */
        public Goods queryByGoodsId(long id)
        {
            using (var db = new OrderContext())
            {
                return db.Goods.FirstOrDefault(p => p.Id == id);
            }
        }
        public List<Goods> getAllGoods()
        {
            using (var db = new OrderContext())
            {
                return db.Goods.ToList();
            }
        }
        public List<OrderDetails> getAllOrderDetails()
        {
            using (var db = new OrderContext())
            {
                return db.OrderDetails.Include("Goods").ToList();
            }
        }
    }
}
